package com.example.cursor_service.impl;

import com.example.cursor_service.RoleService;
import com.example.cursor_orm.model.Role;
import com.example.cursor_orm.dao.RoleDAO;
import com.example.cursor_orm.dao.UserRoleDAO;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.ArrayList;
import com.example.cursor_orm.model.UserRole;

@Service
public class RoleServiceImpl implements RoleService {
    private final RoleDAO roleDAO;
    private final UserRoleDAO userRoleDAO;
    
    public RoleServiceImpl(RoleDAO roleDAO, UserRoleDAO userRoleDAO) {
        this.roleDAO = roleDAO;
        this.userRoleDAO = userRoleDAO;
    }
    
    @Override
    public Role createRole(Role role) {
        try {
            roleDAO.insert(role);
            return role;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public Role getRoleById(Integer id) {
        try {
            return roleDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public Role updateRole(Integer id, Role role) {
        try {
            role.setId(id);
            roleDAO.update(role);
            return roleDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public boolean deleteRole(Integer id) {
        try {
            return roleDAO.deleteById(id) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Role> getRoleList(int page, int size) {
        try {
            List<Role> all = roleDAO.findAll();
            int from = Math.max(0, (page - 1) * size);
            int to = Math.min(all.size(), from + size);
            return all.subList(from, to);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Integer> getUserIdsByRoleId(Integer roleId, int page, int size) {
        try {
            List<Integer> all = new ArrayList<>();
            List<UserRole> userRoles = userRoleDAO.findByRoleId(roleId);
            userRoles.forEach(ur -> all.add(ur.getUserId()));
            int from = Math.max(0, (page - 1) * size);
            int to = Math.min(all.size(), from + size);
            return all.subList(from, to);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean assignRoleToUser(Integer roleId, Integer userId) {
        try {
            return userRoleDAO.assignRoleToUser(userId, roleId) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public boolean removeRoleFromUser(Integer roleId, Integer userId) {
        try {
            return userRoleDAO.removeRoleFromUser(userId, roleId) > 0;
        } catch (Exception e) {
            return false;
        }
    }
} 